package com.chuangke.common.utils;

import static java.util.stream.Collectors.toList;

import java.lang.reflect.InvocationTargetException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.apache.commons.beanutils.BeanMap;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.chuangke.common.exception.ChuangkeException;

public class BeanUtils {

	public static <T> List<Map<String, Object>> beansToMaps(List<T> beans) {
		if (CollectionUtils.isEmpty(beans)) {
			return Collections.emptyList();
		}
		return beans.stream().map(bean -> beanToMap(bean, true)).collect(toList());
	}

	public static <T> Map<String, Object> beanToMap(T bean, boolean ignoreNullValue) {
		BeanMap beanMap = new BeanMap(bean);
		Map<String, Object> map = new HashMap<>(beanMap.size());
		beanMap.forEach((key, value) -> {
			if (ignoreNullValue && Objects.nonNull(value)) {
				map.put(String.valueOf(key), value);
			}
			if (!ignoreNullValue) {
				map.put(String.valueOf(key), value);
			}
		});
		return map;
	}

	public static <T> Map<String, String> beanToMapSS(T bean) {
		try {
			return org.apache.commons.beanutils.BeanUtils.describe(bean);
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			throw new ChuangkeException(e);
		}
	}

	public static Map<String, Object> beanToMapSO(Object bean) {
		return com.baomidou.mybatisplus.core.toolkit.BeanUtils.beanToMap(bean);
	}

	public static Map<Object, Object> beanToMapOO(Object bean) {
		return new BeanMap(bean);
	}

	public static <T> T mapToBean(Map<String, Object> map, Class<T> bean) {
		T t = null;
		try {
			t = bean.getDeclaredConstructor().newInstance();
			org.apache.commons.beanutils.BeanUtils.populate(t, map);
		} catch (Exception e) {
			throw new ChuangkeException(e);
		}
		return t;
	}
}
